package com.cf.expensetracker;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Copyright(C) 2025- com.cf
 * FileName:    ExpenseFileUtil
 * Author:      cf
 * Date:        2025/1/19 19:21
 * Description: Write to and read from a json file
 */
public class ExpenseFileUtil {

    /**
     * Write to a json file
     * @param filename the name of a json file
     * @param result   result entity
     */
    public static void writeToJsonFile(String filename, Result result) {
        Path path = Path.of(filename);

        // Entity to json string
        String jsonString = JSON.toJSONString(result, JSONWriter.Feature.PrettyFormat);

        try {
            Files.writeString(path, jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * Read from a json file
     * @param filename the name of a json file
     * @return Result entity
     */
    public static Result readFromJsonfile(String filename) {
        Result result = new Result();

        Path path = Path.of(filename);

        // json file not exist
        if (!path.toFile().exists()) {
            result.setMaxId(1);
            return result;
        }

        try {
            String content = Files.readString(path);
            // String to Result class
            result = JSON.parseObject(content, Result.class);
        } catch (IOException e) {
            result = null;
            e.printStackTrace();
        }

        return result;
    }
}
